<script setup lang="ts">
// 定义自定义EventSource类型
interface CustomEventSource extends EventSource {
  _messageHandler?: (event: MessageEvent) => void;
  _errorHandler?: (event: Event) => void;
  _closeHandler?: (event: Event) => void;
}

import { ref, onMounted, watch, onUnmounted, computed, nextTick } from 'vue';
import html2canvas from 'html2canvas';
import mermaid from 'mermaid';
import { useI18n } from 'vue-i18n';
import { useChatStore } from '../../stores/chatStore';
import { storeToRefs } from 'pinia';
import { API_CONFIG } from '../../config/apiConfig';
import MessageBubble from './MessageBubble.vue';
import RichTextEditor from './RichTextEditor.vue';
import FilePreview from './FilePreview.vue';
import { currentUser, users } from '../../data/mockData';
import MarkdownIt from 'markdown-it';
import { ToastService } from '../../utils/toastService';

// 初始化MarkdownIt
const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true
});

const { t } = useI18n<{ message: typeof import('../../locales/en-US').default }>();
const chatStore = useChatStore();
const { activeChat } = storeToRefs(chatStore);
const currentMessages = computed(() => {
  if (!activeChat.value) {
    console.log('No active chat');
    return [];
  }
  const messages = chatStore.messages[activeChat.value];
  console.log('Current messages for chat', activeChat.value, ':', messages);
  return messages || [];
});

// SSE连接实例和组件状态
const eventSource = ref<EventSource | null>(null);
const isComponentMounted = ref(true);

const messageText = ref('');
const messagesContainer = ref<HTMLDivElement | null>(null);
// 消息加载状态
const isLoadingMessages = ref(false);
const messageLoadError = ref<string | null>(null);
// 跟踪用户是否已发送消息
const hasUserSentMessage = ref(false);
// 是否正在接收消息
const isReceivingMessage = ref(false);
// 防止按钮快速切换状态
const isButtonDisabled = ref(false);
// 选中的消息索引
const selectedMessages = ref<number[]>([]);
// 编辑器状态
const isEditorVisible = ref(false);
const editorContent = ref('');

// 支持的文件类型
const supportedTypes = [
  'text/plain', // .txt
  'application/pdf', // .pdf
  'application/msword', // .doc
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
  'application/vnd.ms-excel', // .xls
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
  'application/vnd.ms-powerpoint', // .ppt
  'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
  'text/markdown', // .md
  'text/csv', // .csv
  'application/json', // .json
];

// 获取友好的文件类型名称
function getFileTypeLabel(mimeType: string): string {
  const mimeTypeMap: Record<string, string> = {
    'text/plain': 'TXT',
    'application/pdf': 'PDF',
    'application/msword': 'DOC',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'DOCX',
    'application/vnd.ms-excel': 'XLS',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'XLSX',
    'application/vnd.ms-powerpoint': 'PPT',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'PPTX',
    'text/markdown': 'Markdown',
    'text/csv': 'CSV',
    'application/json': 'JSON'
  };
  
  return mimeTypeMap[mimeType] || mimeType;
}

// 文件上传相关状态
const selectedFile = ref<File | null>(null);
const uploadProgress = ref(0);
const fileId = ref<string | null>(null);
const isUploading = ref(false);
const uploadError = ref<string | null>(null);
const fileInputRef = ref<HTMLInputElement | null>(null);

// 切换消息选择状态
const toggleMessageSelection = async (index: number) => {
  // 清除之前的选择
  selectedMessages.value = selectedMessages.value.includes(index) ? [] : [index];
  
  // 如果有选中的消息，则打开编辑器
  if (selectedMessages.value.length > 0) {
    try {
      await openEditor();
    } catch (error) {
      console.error('切换消息选择失败:', error);
      // 回退到关闭编辑器状态
      isEditorVisible.value = false;
      selectedMessages.value = [];
    }
  } else {
    // 如果没有选中的消息，则关闭编辑器
    isEditorVisible.value = false;
  }
};

// 打开富文本编辑器
const openEditor = async () => {
  if (selectedMessages.value.length === 0) return;
  
  try {
    // 获取选中消息的HTML内容
    const convertedContent = await getSelectedMessagesHtml();
    // 确保只保留转换后的图片，移除原始mermaid代码
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = convertedContent;
    const mermaidPreElements = tempDiv.querySelectorAll('pre code.language-mermaid');
    mermaidPreElements.forEach(el => el.remove());
    
    editorContent.value = tempDiv.innerHTML;
    isEditorVisible.value = true;
  } catch (error) {
    console.error('打开编辑器失败:', error);
    // 回退到原始内容
    editorContent.value = selectedMessages.value
      .map(index => currentMessages.value[index])
      .map(message => {
        const renderedContent = md.render(message.content);
        return `<div class="message ${message.senderId === currentUser.id ? 'user' : 'assistant'}">${renderedContent}</div>`;
      })
      .join('\n');
    isEditorVisible.value = true;
  }
};

// 保存编辑器内容
const saveEditorContent = (content: string) => {
  console.log('保存的内容:', content);
  // 这里可以添加保存内容的逻辑，例如保存到本地存储或发送到服务器
  // 暂时只是关闭编辑器
  isEditorVisible.value = false;
  // 清除选择
  selectedMessages.value = [];
};

// 关闭编辑器
const closeEditor = () => {
  isEditorVisible.value = false;
  // 清除选择
  selectedMessages.value = [];
};

// 触发文件选择对话框
function triggerFileInput() {
  if (fileInputRef.value) {
    fileInputRef.value.click();
  }
}

// 处理文件选择
function handleFileSelect(event: Event) {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    const file = input.files[0];
    
    // 检查文件大小限制 (10MB)
    const maxSize = 10 * 1024 * 1024; // 10MB in bytes
    if (file.size > maxSize) {
      uploadError.value = `文件大小超过限制 (最大 10MB)`;
      // 清空文件输入
      if (fileInputRef.value) {
        fileInputRef.value.value = '';
      }
      return;
    }
    
    // 检查文件类型是否支持
    if (!supportedTypes.includes(file.type)) {
      // 获取文件扩展名
      const fileExtension = file.name.split('.').pop()?.toUpperCase() || '';
      
      uploadError.value = `不支持的文件类型: ${fileExtension || getFileTypeLabel(file.type)}`;
      
      // 清空文件输入
      if (fileInputRef.value) {
        fileInputRef.value.value = '';
      }
      return;
    }
    
    selectedFile.value = file;
    uploadError.value = null;
    
    // 自动开始上传
    uploadFile();
  }
}

// 上传文件
async function uploadFile() {
  if (!selectedFile.value) return;
  
  try {
    isUploading.value = true;
    uploadProgress.value = 0;
    uploadError.value = null;
    
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    
    const xhr = new XMLHttpRequest();
    
    // 监听上传进度
    xhr.upload.addEventListener('progress', (event) => {
      if (event.lengthComputable) {
        uploadProgress.value = Math.round((event.loaded / event.total) * 100);
      }
    });
    
    // 创建Promise来处理XHR请求
    const response = await new Promise<any>((resolve, reject) => {
      xhr.open('POST', `${API_CONFIG.BASE_URL}/chat-file`);
      xhr.withCredentials = true; // 包含凭证
      
      xhr.onload = () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const result = JSON.parse(xhr.responseText);
            resolve(result);
          } catch (error) {
            reject(new Error('解析响应失败'));
          }
        } else {
          reject(new Error(`上传失败: ${xhr.status}`));
        }
      };
      
      xhr.onerror = () => reject(new Error('网络错误'));
      xhr.onabort = () => reject(new Error('上传已取消'));
      
      xhr.send(formData);
    });
    
    // 处理响应
    if (response.code === '0' && response.data && response.data.fileId) {
      fileId.value = response.data.fileId;
      ToastService.success('文件上传成功');
      
      // 将文件信息作为消息发送
      const fileName = selectedFile.value?.name || '文件';
      const messageContent = `[文件] ${fileName} (ID: ${response.data.fileId})`;
      
      chatStore.addMessage({
        id: `file-${Date.now()}`,
        content: messageContent,
        senderId: currentUser.id,
        timestamp: new Date(),
        type: 2 // 文件消息类型
      });
    } else if (response.code === '0001') {
      // 会话过期
      chatStore.handleSessionExpired();
      uploadError.value = '会话已过期，请重新登录';
    } else {
      uploadError.value = response.msg || '上传失败';
    }
  } catch (error) {
    ToastService.error('文件上传错误: ' + (error instanceof Error ? error.message : '未知错误'));
    uploadError.value = error instanceof Error ? error.message : '上传失败';
  } finally {
    isUploading.value = false;
    
    // 清空文件输入，以便可以再次选择同一文件
    if (fileInputRef.value) {
      fileInputRef.value.value = '';
    }
  }
}

// 移除已选择的文件
function removeFile() {
  selectedFile.value = null;
  uploadProgress.value = 0;
  fileId.value = null;
  uploadError.value = null;
  
  // 如果正在上传，则中止上传
  if (isUploading.value) {
    isUploading.value = false;
    // 这里可以添加中止XHR请求的逻辑，如果需要的话
  }
  
  // 清空文件输入
  if (fileInputRef.value) {
    fileInputRef.value.value = '';
  }
}

// 重新生成消息
function regenerateMessage() {
  // 查找用户的最后一条消息
  if (!currentMessages.value || currentMessages.value.length === 0) return;
  
  // 从后往前查找用户的最后一条消息
  let lastUserMessage = '';
  for (let i = currentMessages.value.length - 1; i >= 0; i--) {
    if (currentMessages.value[i].senderId === currentUser.id) {
      lastUserMessage = currentMessages.value[i].content;
      break;
    }
  }
  
  // 如果找到了用户的最后一条消息，则重新发送
  if (lastUserMessage) {
    messageText.value = lastUserMessage;
    sendMessage();
  }
}

// 将mermaid图表转换为图片
async function convertMermaidToImage(mermaidElement: HTMLElement): Promise<string> {
  return new Promise((resolve) => {
    const container = document.createElement('div');
    container.style.position = 'absolute';
    container.style.left = '-9999px';
    document.body.appendChild(container);
    container.appendChild(mermaidElement.cloneNode(true));

    const renderMermaid = async () => {
      try {
        // 显式调用mermaid渲染
        await mermaid.run({
          nodes: container.querySelectorAll('.mermaid, pre code.language-mermaid')
        });

        const svg = container.querySelector('svg');
        if (!svg) {
          throw new Error('Mermaid渲染失败，未生成SVG');
        }
        
        // 等待布局更新
        await new Promise(resolve => requestAnimationFrame(resolve));
        
        // 计算实际需要的截图尺寸
        const canvas = await html2canvas(container, {
        scale: Math.max(2, window.devicePixelRatio),
        useCORS: true,
        allowTaint: false,
        logging: true
      });

        const imgData = canvas.toDataURL('image/png');
        console.log('转换成功，图片数据:', imgData?.substring(0, 50) + '...');
        resolve(imgData);
      } catch (error) {
        console.error('转换mermaid图表失败:', error);
        resolve('');
      } finally {
        // 清理临时元素
        document.body.removeChild(container);
      }
    };

    // 设置超时
    const timeout = setTimeout(() => {
      console.error('Mermaid渲染超时');
      document.body.removeChild(container);
      resolve('');
    }, 5000);

    renderMermaid().then(() => {
      clearTimeout(timeout);
    });
  });
}

// 获取选中消息的HTML内容
async function getSelectedMessagesHtml() {
  let result = '';
  
  for (const index of selectedMessages.value) {
    const message = currentMessages.value[index];
    let renderedContent = md.render(message.content);
    
    // 创建临时div来检测和转换mermaid图表
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = renderedContent;
    document.body.appendChild(tempDiv);
    
    // 转换所有mermaid图表为图片
    const mermaidElements = tempDiv.querySelectorAll('pre code.language-mermaid');
    console.log('找到的mermaid元素数量:', mermaidElements.length);
    for (const element of mermaidElements) {
      console.log('开始转换mermaid元素:', element);
      const imgData = await convertMermaidToImage(element.parentElement as HTMLElement);
      console.log('转换完成，结果:', imgData ? '成功' : '失败');
      if (imgData) {
        const img = document.createElement('img');
        img.src = imgData;
        img.style.maxWidth = '100%';
        img.alt = 'Mermaid Chart';
        element.replaceWith(img);
      }
    }
    
    // 获取处理后的HTML
    renderedContent = tempDiv.innerHTML;
    document.body.removeChild(tempDiv);
    
    // 添加到结果中
    result += `<div class="message ${message.senderId === currentUser.id ? 'user' : 'assistant'}">${renderedContent}</div>\n`;
  }
  
  return result;
}

// 计算属性
const showEmptyState = computed(() => {
  // 如果用户尚未发送消息，总是显示空状态
  if (!hasUserSentMessage.value) {
    return true;
  }
  // 否则使用原来的逻辑
  return !activeChat.value || (activeChat.value && currentMessages.value.length === 0);
});

const emptyStateTitle = computed(() => {
  if (!activeChat.value) {
    return t('chat.emptyChat');
  }
  return t('chat.emptyChat');
});

const emptyStateDescription = computed(() => {
  if (!activeChat.value) {
    return t('chat.emptyDescription');
  }
  return t('chat.emptyDescription');
});

// 清理SSE连接
function cleanupSSE() {
  if (eventSource.value) {
    const customSource = eventSource.value as CustomEventSource;
    if (customSource instanceof EventSource) {
      try {
        // 移除所有事件监听器
        if (customSource._messageHandler) {
          customSource.removeEventListener('message', customSource._messageHandler);
          customSource._messageHandler = undefined;
        }
        if (customSource._errorHandler) {
          customSource.removeEventListener('error', customSource._errorHandler);
          customSource._errorHandler = undefined;
        }
        if (customSource._closeHandler) {
          customSource.removeEventListener('close', customSource._closeHandler);
          customSource._closeHandler = undefined;
        }
        
        // 强制关闭连接
        customSource.close();
      } catch (error) {
        console.error('Error closing SSE connection:', error);
      } finally {
        eventSource.value = null;
        isReceivingMessage.value = false;
        console.log('SSE连接已关闭');
      }
    }
  }
}

async function sendMessage() {
  // 如果按钮被禁用，直接返回
  if (isButtonDisabled.value) return;
  
  // 如果正在接收消息，则停止接收
  if (isReceivingMessage.value) {
    isButtonDisabled.value = true;
    stopReceivingMessage();
    // 300ms后恢复按钮状态
    setTimeout(() => {
      isButtonDisabled.value = false;
    }, 300);
    return;
  }

  if (!messageText.value.trim()) return;
  
  // 设置用户已发送消息标志
  hasUserSentMessage.value = true;
  // 设置正在接收消息状态
  isReceivingMessage.value = true;
  
  const message = messageText.value.trim();
  const encodedMessage = encodeURIComponent(message);

  // 如果没有活动会话，先创建一个新会话
  if (!activeChat.value) {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/chat`, {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          type: chatStore.currentChatType
        })
      });
      
      const res = await response.json();
      if (res.code === "0") {
        const chatId = res.data;
        // 将新会话添加到列表
        const newChat = {
          id: chatId,
          name: t('chat.newSession'),
          participants: [],
          lastMessage: {
            id: '',
            content: '',
            senderId: '',
            timestamp: new Date()
          }
        };
        
        // 添加到store中并设置为当前活动会话
        chatStore.addChat(newChat);
        chatStore.setActiveChat(chatId);
      } else if (res.code === "0001") {
        // 处理会话过期
        chatStore.handleSessionExpired();
        isReceivingMessage.value = false;
        return;
      } else {
        console.error('创建会话失败:', res.msg);
        isReceivingMessage.value = false;
        return;
      }
    } catch (error) {
      console.error('创建会话失败:', error);
      isReceivingMessage.value = false;
      return;
    }
  }

  // 添加用户消息到聊天记录
  chatStore.addMessage({
    id: `user-${Date.now()}`,
    content: message,
    senderId: currentUser.id,
    timestamp: new Date(),
  });

  // 清空输入框并处理消息队列
  messageText.value = '';
  await processMessageQueue();

  // 关闭现有的SSE连接
  cleanupSSE();

  try {
    // 创建临时消息用于显示助手的回复
    const tempMessageId = `assistant-${Date.now()}`;
    chatStore.addMessage({
      id: tempMessageId,
      content: '思考中...',
      senderId: 'assistant',
      timestamp: new Date(),
    });

    // 根据聊天类型构建不同的SSE连接URL
    const chatTypeEndpoint = chatStore.currentChatType === 0 ? 'high/chat' : 'inventory/chat';
    
    // 构建URL，如果有文件ID则添加到URL中
    let sseUrl = `${API_CONFIG.BASE_URL}/${chatTypeEndpoint}?memoryId=${activeChat.value}&message=${encodedMessage}`;
    if (fileId.value) {
      sseUrl += `&fileId=${fileId.value}`;
    }
    
    // 建立新的SSE连接
    const source = new EventSource(sseUrl, { withCredentials: true });
    eventSource.value = source;

    let accumulatedContent = '';
    let isFirstMessage = true;

    // 保存事件处理函数引用以便后续移除
    const messageHandler = (event: MessageEvent) => {
      try {
        const data = JSON.parse(event.data);
        if (data.content) {
          // 如果是第一条消息，直接替换"思考中..."
          if (isFirstMessage) {
            accumulatedContent = data.content;
            isFirstMessage = false;
          } else {
            accumulatedContent += data.content;
          }
          
          if (activeChat.value && chatStore.messages[activeChat.value]) {
            const messages = chatStore.messages[activeChat.value];
            
            // 更新实际回复消息
            const tempMessageIndex = messages.findIndex(msg => msg.id === tempMessageId);
            if (tempMessageIndex !== -1) {
              messages[tempMessageIndex].content = accumulatedContent;
              scrollToBottom();
            }
          }
        } else if (data.contentSourceList) {
          // 处理引用部分
          if (activeChat.value && chatStore.messages[activeChat.value]) {
            const messages = chatStore.messages[activeChat.value];
            const tempMessageIndex = messages.findIndex(msg => msg.id === tempMessageId);
            if (tempMessageIndex !== -1) {
              messages[tempMessageIndex].contentSourceList = data.contentSourceList;
            }
          }
        }
      } catch (error) {
        console.error('Error parsing SSE message:', error);
      }
    };

    const errorHandler = (event: Event) => {
      // 尝试解析错误信息
      let errorData = null;
      try {
        // 如果event有data属性，尝试解析它
        if ('data' in event && typeof (event as any).data === 'string') {
          errorData = JSON.parse((event as any).data);
        }
      } catch (e) {
        console.error('解析SSE错误数据失败:', e);
      }
      
      // 检查是否是会话过期错误
      if (errorData && errorData.code === '0001') {
        // 调用chatStore中的会话过期处理方法
        chatStore.handleSessionExpired();
      } else {
        // 常规错误处理
        if (activeChat.value && chatStore.messages[activeChat.value]) {
          const messages = chatStore.messages[activeChat.value];
          
          // 如果没有收到任何内容，更新临时消息为错误消息
          const tempMessageIndex = messages.findIndex(msg => msg.id === tempMessageId);
          if (tempMessageIndex !== -1) {
            if (!accumulatedContent) {
              messages[tempMessageIndex].content = t('chat.responseError');
            }
          }
        }
      }
      
      cleanupSSE();
      isReceivingMessage.value = false;
    };

    const closeHandler = () => {
      cleanupSSE();
      isReceivingMessage.value = false;
    };

    // 确保eventSource存在且是EventSource实例
    const customSource = source as CustomEventSource;
    if (customSource instanceof EventSource) {
      // 添加事件监听器
      customSource.addEventListener('message', messageHandler);
      customSource.addEventListener('error', errorHandler);
      customSource.addEventListener('close', closeHandler);

      // 保存处理函数引用以便后续移除
      customSource._messageHandler = messageHandler;
      customSource._errorHandler = errorHandler;
      customSource._closeHandler = closeHandler;
    } else {
      console.error('Failed to create SSE connection');
      isReceivingMessage.value = false;
      return;
    }

  } catch (error) {
    console.error('Error sending message:', error);
    // 在消息窗口显示错误信息
    chatStore.addMessage({
      id: `error-${Date.now()}`,
      content: `${t('chat.sendError')}: ${error instanceof Error ? error.message : t('common.unknownError')}`,
      senderId: 'assistant',
      timestamp: new Date()
    });
    // 重置状态
    isReceivingMessage.value = false;
    messageLoadError.value = 'Failed to send message';
  } finally {
    // 清理文件上传状态
    selectedFile.value = null;
    uploadProgress.value = 0;
    fileId.value = null;
    uploadError.value = null;
    
    // 清空文件输入
    if (fileInputRef.value) {
      fileInputRef.value.value = '';
    }
  }
}

// 停止接收消息
function stopReceivingMessage() {
  cleanupSSE();
  
  // 添加停止后的反馈
  if (activeChat.value && chatStore.messages[activeChat.value]) {
    const messages = chatStore.messages[activeChat.value];
    
    const lastMessage = messages[messages.length - 1];
    if (lastMessage && lastMessage.senderId === 'assistant') {
      // 如果最后一条消息是助手的，添加停止生成的提示
      lastMessage.content += '\n\n(已停止生成)';
    }
  }
}

function handleKeyDown(event: KeyboardEvent) {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
}

function adjustTextareaHeight(event: Event) {
  const textarea = event.target as HTMLTextAreaElement;
  textarea.style.height = 'auto';
  textarea.style.height = `${textarea.scrollHeight}px`;
}

// 优化后的滚动函数
function scrollToBottom(behavior: ScrollBehavior = 'smooth') {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTo({
        top: messagesContainer.value.scrollHeight,
        behavior,
      });
    }
  });
}

// 处理消息队列
async function processMessageQueue() {
  if (isReceivingMessage.value) return;
  
  isLoadingMessages.value = true;
  messageLoadError.value = null;

  try {
    // 确保消息按顺序处理
    await new Promise(resolve => setTimeout(resolve, 50));
    scrollToBottom('auto');
    
    // 添加超时处理
    await new Promise((resolve, reject) => {
      const timeout = setTimeout(() => {
        reject(new Error('消息加载超时'));
      }, 30000); // 30秒超时
      
      // 监听消息接收完成
      const unwatch = watch(() => !isReceivingMessage.value, (val) => {
        if (val) {
          clearTimeout(timeout);
          resolve(true);
        }
      });
      
      // 确保清理
      onUnmounted(() => {
        clearTimeout(timeout);
        unwatch();
      });
    });
  } catch (error) {
    messageLoadError.value = error instanceof Error ? error.message : '处理消息失败';
    console.error('Error processing message queue:', error);
    
    // 添加错误消息到聊天
    if (activeChat.value) {
      chatStore.addMessage({
        id: `error-${Date.now()}`,
        content: `消息处理错误: ${messageLoadError.value}`,
        senderId: 'system',
        timestamp: new Date()
      });
    }
  } finally {
    isLoadingMessages.value = false;
  }
}

onMounted(() => {
  isComponentMounted.value = true;
  // 重置用户发送消息状态
  hasUserSentMessage.value = false;
  
  // 初始化mermaid配置
  mermaid.initialize({
    startOnLoad: false,
    theme: 'default',
    flowchart: { useMaxWidth: true },
    securityLevel: 'loose'
  });
  
  scrollToBottom();
});

onUnmounted(() => {
  isComponentMounted.value = false;
  cleanupSSE();
});

// 监听消息变化，自动滚动到底部
watch(currentMessages, () => {
  if (isComponentMounted.value) {
    scrollToBottom();
  }
}, { deep: true });

// 监听聊天切换
watch(activeChat, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    cleanupSSE();
    scrollToBottom();
    
    // 如果用户点击了聊天项，则显示聊天内容而不是空状态
    if (newVal) {
      hasUserSentMessage.value = true;
    } else {
      // 如果没有选中聊天，则重置状态
      hasUserSentMessage.value = false;
    }
    
    // 清除选择
    selectedMessages.value = [];
    isEditorVisible.value = false;
  }
});


</script>

<template>
  <div class="chat-container">
    <!-- AI助手信息卡片 -->
    <div class="ai-assistant-card" v-if="showEmptyState">
      <div class="assistant-avatar">
        <div class="avatar-icon">⚛️</div>
        <div class="status-indicator">
          <div class="status-dot"></div>
          <span>未来AI引擎 by 先途科技</span>
        </div>
      </div>
      <div class="assistant-info">
        <h2>{{ emptyStateTitle }}</h2>
        <p>{{ emptyStateDescription }}</p>
        
        <!-- 能力展示 -->
        <div class="capabilities-container">
          <h3 class="capabilities-title">💡 核心能力展示</h3>
          <div class="capabilities-grid">
            <div class="capability-card">
              <div class="card-icon">🔍</div>
              <h4 class="card-title">深度文献检索与分析</h4>
              <p class="card-desc">快速定位相关文献，智能提取关键信息</p>
            </div>
            <div class="capability-card">
              <div class="card-icon">📊</div>
              <h4 class="card-title">高级数据组织与可视化</h4>
              <p class="card-desc">结构化数据呈现，多维度分析展示</p>
            </div>
            <div class="capability-card">
              <div class="card-icon">✍️</div>
              <h4 class="card-title">AI驱动的论文写作指导</h4>
              <p class="card-desc">从提纲到润色，全程智能辅助</p>
            </div>
            <div class="capability-card">
              <div class="card-icon">🎯</div>
              <h4 class="card-title">前沿研究方法建议</h4>
              <p class="card-desc">基于最新研究趋势的方法论推荐</p>
            </div>
          </div>
        </div>
        
        <div class="welcome-note">
          <span class="note-icon">💡</span>
          <span>请详述您的研究需求，让我们开始探索知识的边界！</span>
        </div>
      </div>
    </div>
    
    <div class="chat-area" v-if="activeChat">
      <div v-if="currentMessages && currentMessages.length > 0" class="messages" ref="messagesContainer">
        <TransitionGroup name="fade">
          <MessageBubble 
            v-for="(message, index) in currentMessages"
            :key="message.id || `temp-${index}`"
            :message="message"
            :is-current-user="message.senderId === currentUser.id"
            :sender="message.senderId === currentUser.id ? currentUser : users.find(u => u.id === message.senderId)"
            :index="index"
            :is-selected="selectedMessages.includes(index)"
            :is-complete="!isReceivingMessage || message.senderId !== 'assistant'"
            :total-messages="currentMessages.length"
            @toggle-select="toggleMessageSelection"
            @show-mindmap="$emit('show-mindmap', $event)"
            @regenerate="regenerateMessage"
          />
        </TransitionGroup>
      </div>
      <div v-else class="no-messages">
        <p>暂无消息记录</p>
      </div>
    </div>
    
    <div class="message-input-container">
      <!-- 文件预览区域 -->
      <div v-if="selectedFile" class="file-preview-container">
        <FilePreview 
          :file="selectedFile" 
          :progress="uploadProgress" 
          :is-uploading="isUploading" 
          @remove="removeFile" 
        />
        <div v-if="uploadError" class="upload-error">{{ uploadError }}</div>
      </div>
      
      <div class="message-input-wrapper">
        <!-- 隐藏的文件输入框 -->
        <input 
          type="file" 
          ref="fileInputRef" 
          class="file-input" 
          @change="handleFileSelect" 
          accept=".txt,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.md,.csv,.json"
        />
        
        <!-- 文件上传按钮 -->
        <button 
          class="attachment-button" 
          @click="triggerFileInput"
          :disabled="isUploading || isReceivingMessage"
          :title="t('chat.attachFile') + ' (支持: TXT, PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, MD, CSV, JSON)'"
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path>
          </svg>
        </button>
        
        <textarea
          :placeholder="t('chat.inputPlaceholder')" 
          class="message-input"
          v-model="messageText"
          @keydown="handleKeyDown"
          rows="1"
          @input="adjustTextareaHeight"
        ></textarea>
        
        <button 
          :class="[
            'send-button',
            isReceivingMessage ? 'receiving' : ''
          ]"
          :disabled="isButtonDisabled || (!isReceivingMessage && !messageText.trim() && !fileId)"
          @click="sendMessage"
        >
          <svg v-if="!isReceivingMessage" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22,2 15,22 11,13 2,9"></polygon>
          </svg>
          <svg v-else xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="6" y="4" width="4" height="16"></rect>
            <rect x="14" y="4" width="4" height="16"></rect>
          </svg>
        </button>
      </div>
    </div>
  </div>
  
  <!-- 富文本编辑器 -->
  <RichTextEditor
    :is-visible="isEditorVisible"
    :content="editorContent"
    @save="saveEditorContent"
    @close="closeEditor"
  />
</template>

<style scoped>
.capabilities-container {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.capabilities-title {
  text-align: center;
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  color: var(--text-primary);
  font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
}

.capabilities-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(220px, 1fr));
  gap: 1.25rem;
}

.capability-card {
  padding: 1.5rem;
  background: rgba(255, 255, 255, 0.92);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.4);
  border-radius: 1rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  text-align: center;
  min-height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.capability-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(
    135deg,
    rgba(102, 126, 234, 0.05) 0%,
    rgba(118, 75, 162, 0.05) 100%
  );
  opacity: 0;
  transition: opacity 0.3s ease;
}

.capability-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.98);
  border-color: rgba(102, 126, 234, 0.2);
}

.capability-card:hover::before {
  opacity: 1;
}

.card-icon {
  font-size: 2rem;
  margin-bottom: 0.75rem;
  color: var(--primary);
}

.card-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: var(--text-primary);
  font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
}

.card-desc {
  font-size: 0.9rem;
  color: var(--text-secondary);
  line-height: 1.5;
  font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .capabilities-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 640px) {
  .capabilities-grid {
    grid-template-columns: 1fr;
  }
  
  .capability-card {
    min-height: auto;
    padding: 1.25rem;
  }
}

.no-messages {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #a0aec0;
  font-size: 14px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-enter-from {
  opacity: 0;
  transform: translateY(10px);
}

.fade-leave-to {
  opacity: 0;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  overflow: hidden;
  position: relative;
  max-width: 1600px;
  margin: 0 auto;
  width: 100%;
}

/* AI助手信息卡片 */
.ai-assistant-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
}

.assistant-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
}

.avatar-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  margin-bottom: 16px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #10b981;
  font-size: 14px;
  font-weight: 500;
}

.status-dot {
  width: 8px;
  height: 8px;
  background: #10b981;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(16, 185, 129, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
  }
}

.assistant-info h2 {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  margin-bottom: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.assistant-info p {
  font-size: 16px;
  color: #718096;
  margin-bottom: 32px;
  line-height: 1.6;
}

.capabilities {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  text-align: left;
  max-width: 500px;
}

.capabilities h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.capability-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.capability-list li {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  font-size: 14px;
  color: #4a5568;
}

.capability-icon {
  font-size: 16px;
  width: 20px;
  text-align: center;
}

.welcome-note {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(102, 126, 234, 0.1);
  padding: 16px 20px;
  border-radius: 12px;
  color: #667eea;
  font-size: 14px;
  font-weight: 500;
  max-width: 500px;
}

.note-icon {
  font-size: 16px;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  height: 100%;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 100px; /* 输入框区域的最小高度 */
  padding-bottom: 40px; /* 额外的底部内边距，确保最后一条消息可见 */
  scroll-behavior: smooth;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

@media (min-width: 1600px) {
  .messages {
    padding: 20px 40px;
  }
}

@media (max-width: 768px) {
  .messages {
    padding: 16px;
    bottom: 80px;
  }
}

.messages::-webkit-scrollbar {
  width: 6px;
}

.messages::-webkit-scrollbar-track {
  background: transparent;
}

.messages::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.3);
}

.message-input-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  min-height: 80px;
  max-height: 200px;
  z-index: 10;
  transition: min-height 0.2s ease;
}

.message-input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 24px;
  padding: 12px 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.message-input-wrapper:focus-within {
  border-color: rgba(102, 126, 234, 0.5);
  box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1), 0 4px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.file-input {
  display: none;
}

.attachment-button {
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: none;
  cursor: pointer;
  color: #6b7280;
  transition: all 0.2s;
  padding: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.attachment-button:hover {
  color: #667eea;
  background-color: rgba(102, 126, 234, 0.1);
}

.attachment-button:disabled {
  color: #d1d5db;
  cursor: not-allowed;
  background-color: transparent;
}

.message-input {
  flex: 1;
  border: none;
  background: transparent;
  padding: 10px 0;
  font-size: 15px;
  outline: none;
  resize: none;
  overflow-y: auto;
  min-height: 24px;
  max-height: 120px;
  line-height: 1.5;
  transition: height 0.2s ease;
  color: #2d3748;
  margin-right: 8px;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
}

.message-input::-webkit-scrollbar {
  width: 4px;
}

.message-input::-webkit-scrollbar-track {
  background: transparent;
}

.message-input::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 2px;
}

.message-input::placeholder {
  color: #a0aec0;
}

.send-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  position: relative;
  overflow: hidden;
}

.send-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.send-button:hover:not(:disabled)::before {
  opacity: 1;
}

.send-button:hover:not(:disabled) {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.send-button:active:not(:disabled) {
  transform: translateY(1px) scale(0.95);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.send-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
  background: linear-gradient(135deg, #a0aec0 0%, #718096 100%);
}

.send-button.receiving {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
  animation: pulse 2s infinite;
}

.send-button.receiving:hover {
  box-shadow: 0 6px 20px rgba(239, 68, 68, 0.4);
  transform: translateY(-2px) scale(1.05);
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
  }
}

/* 文件预览容器 */
.file-preview-container {
  margin-bottom: 12px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 12px;
}

/* 上传错误提示 */
.upload-error {
  display: flex;
  align-items: center;
  color: #ef4444;
  font-size: 0.875rem;
  margin-top: 8px;
  padding: 8px 12px;
  background-color: rgba(239, 68, 68, 0.1);
  border-left: 3px solid #ef4444;
  border-radius: 4px;
}

.upload-error::before {
  content: "⚠️";
  margin-right: 8px;
  font-size: 1rem;
}

/* 自定义滚动条 */
.messages::-webkit-scrollbar {
  width: 6px;
}

.messages::-webkit-scrollbar-track {
  background: transparent;
}

.messages::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.3);
}

@media (max-width: 768px) {
  .chat-container {
    margin: 0;
    border-radius: 0;
  }
  
  .ai-assistant-card {
    padding: 20px;
  }
  
  .assistant-info h2 {
    font-size: 24px;
  }
  
  .capabilities {
    padding: 16px;
  }
  
  .message-input-container {
    padding: 16px;
  }
}
</style>